﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Administration.UserManagement.sMenuHandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;
using SIPO.Library.DataAccess.Administration.UserManagement;
using SIPO.Library.DomainObject.Administration.UserManagement;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;
using System.Configuration;

namespace SIPO.Web.AjaxHandler.Administration.UserManagement
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>

    public class sMenuHandler : BaseHandler
    {

        private recMenuRepo menuDal = new recMenuRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);

        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);            

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recMenu menu = new recMenu();
                menu.MenuName = (string)jo["MenuName"];
                menu.OrderSeq = string.IsNullOrEmpty((string)jo["OrderSeq"]) ? (short?)null : Convert.ToInt16(jo["OrderSeq"]);
                menu.ParentMenuID = (string.IsNullOrEmpty((string)jo["ParentID"]) ? (int?)null : Convert.ToInt32(jo["ParentID"]));
                menu.URL = (string)jo["URL"];

                menu.CreatedDate = DateTime.Now;
                menu.CreatedBy = base.UserLoggedIn;

                menuDal.Save(menu);

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {

                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "sMenuhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recMenu menu = new recMenu();

                menu.MenuID = Convert.ToInt32(jo["MenuID"]);      
                menu.MenuName = (string)jo["MenuName"];
                menu.OrderSeq = string.IsNullOrEmpty((string)jo["OrderSeq"]) ? (short?)null : Convert.ToInt16(jo["OrderSeq"]);
                menu.ParentMenuID = (string.IsNullOrEmpty((string)jo["ParentID"]) ? (int?)null : Convert.ToInt32(jo["ParentID"]));
                menu.URL = (string)jo["URL"];
                
                menu.UpdatedDate = DateTime.Now;
                menu.UpdatedBy = base.UserLoggedIn;

                menuDal.Update(menu);

                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "sMenuhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["MenuID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    menuDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally {
                
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "sMenuhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);            
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recMenu.Fields.OrderSeq : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());
            
            List<recMenu> list = menuDal.GetHierarchyList(parameters);
            var pagedList = list.Skip((page - 1) * pageSize).Take(pageSize);

            int totalCount = list.Count;
            decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
            int totalPages = Convert.ToInt32(dc);

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        #endregion


    }
}
